/**
 * 投票系统 Composable
 */
import { ref, computed } from 'vue'

export function useVoteSystem() {
  // 响应式数据
  const activeVote = ref(null)
  const voteHistory = ref([])
  const hasVoted = ref(false)
  const userVote = ref(null)
  const voteLoading = ref(false)
  const voteError = ref('')

  // 计算属性
  const showVoteSection = computed(() => {
    // 这个计算属性需要从外部传入相关数据，或者改为通过参数传入
    return false // 暂时返回false，需要在调用时传入相关数据
  })

  const canInitiateVote = computed(() => {
    // 这个计算属性需要从外部传入相关数据，或者改为通过参数传入
    return false // 暂时返回false，需要在调用时传入相关数据
  })

  // 方法
  const fetchActiveVote = async (teamId) => {
    if (!teamId) return

    voteLoading.value = true
    voteError.value = ''

    try {
      const token = uni.getStorageSync('accessToken')
      if (!token) {
        throw new Error('请先登录')
      }

      const response = await uni.request({
        url: `${NETWORK_CONFIG.API_BASE_URL}/team-vote/active/${teamId}`,
        method: 'GET',
        header: {
          'Access-Token': `Bearer ${token}`
        }
      })

      if (response.data && response.data.success) {
        activeVote.value = response.data.data
        hasVoted.value = response.data.hasVoted || false
        userVote.value = response.data.userVote
      }
    } catch (err) {
      voteError.value = err.message || '获取投票信息失败'
      console.error('获取投票信息失败:', err)
    } finally {
      voteLoading.value = false
    }
  }

  const fetchVoteHistory = async (teamId) => {
    if (!teamId) return

    try {
      const token = uni.getStorageSync('accessToken')
      if (!token) {
        throw new Error('请先登录')
      }

      const response = await uni.request({
        url: `${NETWORK_CONFIG.API_BASE_URL}/team-vote/history/${teamId}`,
        method: 'GET',
        header: {
          'Access-Token': `Bearer ${token}`
        }
      })

      if (response.data && response.data.success) {
        voteHistory.value = response.data.data || []
      }
    } catch (err) {
      console.error('获取投票历史失败:', err)
    }
  }

  const submitVote = async (voteId, approve) => {
    if (!voteId) return

    try {
      const token = uni.getStorageSync('accessToken')
      if (!token) {
        throw new Error('请先登录')
      }

      const response = await uni.request({
        url: '${NETWORK_CONFIG.API_BASE_URL}/team-vote/vote',
        method: 'POST',
        data: {
          voteId: voteId,
          approve: approve
        },
        header: {
          'Access-Token': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })

      if (response.data && response.data.success) {
        hasVoted.value = true
        userVote.value = approve
        uni.showToast({
          title: '投票成功',
          icon: 'success'
        })
        return true
      } else {
        throw new Error(response.data?.message || '投票失败')
      }
    } catch (err) {
      console.error('投票失败:', err)
      uni.showToast({
        title: err.message || '投票失败',
        icon: 'none'
      })
      return false
    }
  }

  const initiateRemoveVote = async (teamId, targetUserId, reason) => {
    if (!teamId || !targetUserId) return

    try {
      const token = uni.getStorageSync('accessToken')
      if (!token) {
        throw new Error('请先登录')
      }

      const response = await uni.request({
        url: '${NETWORK_CONFIG.API_BASE_URL}/team-vote/initiate-remove',
        method: 'POST',
        data: {
          teamId: teamId,
          targetUserId: targetUserId,
          reason: reason
        },
        header: {
          'Access-Token': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })

      if (response.data && response.data.success) {
        uni.showToast({
          title: '踢人投票已发起',
          icon: 'success'
        })
        // 刷新投票信息
        await fetchActiveVote(teamId)
        return true
      } else {
        throw new Error(response.data?.message || '发起投票失败')
      }
    } catch (err) {
      console.error('发起踢人投票失败:', err)
      uni.showToast({
        title: err.message || '发起投票失败',
        icon: 'none'
      })
      return false
    }
  }

  const initiateImpeachVote = async (teamId, reason) => {
    if (!teamId) return

    try {
      const token = uni.getStorageSync('accessToken')
      if (!token) {
        throw new Error('请先登录')
      }

      const response = await uni.request({
        url: '${NETWORK_CONFIG.API_BASE_URL}/team-vote/initiate-impeach',
        method: 'POST',
        data: {
          teamId: teamId,
          reason: reason
        },
        header: {
          'Access-Token': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })

      if (response.data && response.data.success) {
        uni.showToast({
          title: '弹劾投票已发起',
          icon: 'success'
        })
        // 刷新投票信息
        await fetchActiveVote(teamId)
        return true
      } else {
        throw new Error(response.data?.message || '发起投票失败')
      }
    } catch (err) {
      console.error('发起弹劾投票失败:', err)
      uni.showToast({
        title: err.message || '发起投票失败',
        icon: 'none'
      })
      return false
    }
  }

  const getVoteTypeText = (voteType) => {
    const typeMap = {
      1: '踢人投票',
      2: '弹劾队长',
      3: '选举新队长'
    }
    return typeMap[voteType] || '未知类型'
  }

  const getVoteStatusText = (status) => {
    const statusMap = {
      0: '进行中',
      1: '已通过',
      2: '已拒绝',
      3: '已超时'
    }
    return statusMap[status] || '未知状态'
  }

  return {
    // 响应式数据
    activeVote,
    voteHistory,
    hasVoted,
    userVote,
    voteLoading,
    voteError,
    
    // 计算属性
    showVoteSection,
    canInitiateVote,
    
    // 方法
    fetchActiveVote,
    fetchVoteHistory,
    submitVote,
    initiateRemoveVote,
    initiateImpeachVote,
    getVoteTypeText,
    getVoteStatusText
  }
}
